<?php

namespace App\Admin\Controllers;

use App\Models\Goods;
use App\Models\GoodsClassify;
use App\Models\GoodsSku;
use App\Models\Sharp;
use App\Models\SharpToGoods;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class SharpGoodsSkuController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id, Content $content)
    {
    	$default = SharpToGoods::with(['goods:id', 'goods.classify:id,title', 'goods.goodsSku:id,goods_id,attribute_string'])
		    ->where('sharp_id', $id)
		    ->whereNotNull('goods_sku_id')
		    ->get();
    	
    	$goodsClassify = GoodsClassify::where('store_id', Admin::user()->store_id)->get(['id', 'title']);
    	$goods = Goods::whereIn('id', array_keys($default->pluck('goods_id', 'goods_id')->toArray()))
		    ->withTrashed()->get(['id', 'name']);
    	
	    $goodsSku = [];
	    $default->map(function ($item) use (&$goodsSku) {
	    	foreach ($item->goods->goodsSku as $k => $v) {
	    	    if ($item->goods_sku_id == $v->id) {
	    	    	$goodsSku[$item->goods_id] = [
	    	    		$v->id => $v->attribute_string
			        ];
		        }
		    }
	    });
	    
	    $goodsClassify = $goodsClassify->pluck('title', 'id');
	    
	    return $content->header('添加秒杀商品')
		        ->row(view('admin.sharps.box-header', ['title' => '有属性规格']))
		        ->body(view('admin.sharps.sharp-edit', compact('id', 'default', 'goodsClassify', 'goods', 'goodsSku')));
    }

    /**
     * 更新秒杀商品
     * I：返回不为零的库存
     * II：删除sharp_id关联列
     * III：减少库存并且重新创建关联列
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $param = $request->only(['id', 'numbers', 'materials', 'price', 'skus', 'linePrice']);
        $validate = Validator::make($param, [
            'id' => 'required',
		    'numbers' => 'required',
		    'materials' => 'required',
		    'price' => 'required',
		    'skus' => 'required',
		    'linePrice' => 'required'
        ]);
        if ($validate->fails()) {
        	return json(400, 1, $validate->errors()->first(), $param);
        }
        $data = [];
		for ($i = 0; $i < count($param['price']); $i++) {
			$data[] = [
				'sharp_id' => $id,
				'goods_id' => $param['materials'][$i]['material_id'],
				'goods_sku_id' => $param['skus'][$i]['sku'],
				'stock' => $param['numbers'][$i]['number'],
				'price' => $param['price'][$i]['price'] * 100,
				'line_price' => $param['linePrice'][$i]['linePrice'] * 100,
				'created_at' => Carbon::now(),
				'updated_at' => Carbon::now()
			];
		}
		//活动开始前可以修改
	    $goods = SharpToGoods::where('sharp_id', $id)->get()->toArray();
		$sharp = Sharp::find($id);
		if (!empty($goods) && $sharp->active_start < Carbon::now()) {
			return json(400, 1, '活动已经开始，不方便再修改');
		}
		$res = true;
		//返回秒杀sku库存
	    SharpToGoods::prepareReturnStock( $id);
		//减少库存
	    $res = SharpToGoods::prepareReduceStock(collect($data)->pluck('stock', 'goods_sku_id')->toArray());

		if ($res !== true) {
			return json(400, 1, $res, $data);
		}
	    // 删除关联
	    SharpToGoods::where('sharp_id', $id)->delete();
        $res = DB::table('sharp_to_goods')->insert($data);
        
        if ($res) {
        	return response([
        		'status' => 201,
		        'code' => 1,
		        'msg' => '创建成功',
		        'data' => $data
	        ]);
        } else {
        	return response([
        		'status' => 500,
		        'code' => 1,
		        'msg' => '创建失败',
		        'data' => $data
	        ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    
    public function getGoods(Request $request)
    {
	    $param = $request->all();
        $validate = Validator::make($request->all(), [
        	'goods_classify_id' => 'required',
        ]);
        if($validate->fails()){
        	return response(['code' => 1, 'msg' => $validate->errors()->first()]);
        }
        $goods = GoodsClassify::with(['goods' => function ($q) use ($param) {
            $q->whereNotIn('goods_id', $param['material_id'])->selectRaw('goods_id as id,name');
        }])->find($param['goods_classify_id']);
        
        $data = [];
        foreach ($goods->goods as $k => $v) {
            $data[] = $v;
        }
        return response([
        	'code' => 1,
	        'msg' => '查询成功',
	        'data' => $data
        ]);
    }
    
    public function getSku(Request $request)
    {
        $param = $request->all();
        $validate = Validator::make($param, [
        	'goods_id' => 'required'
        ]);
        if($validate->fails()) {
        	return response([
        		'status' => 400,
		        'code' => 1,
		        'msg' => $validate->errors()->first(),
		        'data' => $param
	        ]);
        }
        
        $sku = GoodsSku::where('goods_id', $param['goods_id'])->get();
        $data = [];
        $sku->map(function ($item) use (&$data) {
            $data[] = [
            	'id' => $item->id,
            	'attribute_string' => $item->attribute_string,
            ];
        });
        
        return response([
        	'status' => 200,
	        'code' => 1,
	        'msg' => '查询成功',
	        'data' => $data
        ]);
    }
}
